// ignore_for_file: unused_import

import 'dart:math';
import 'package:provider/provider.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_chat_i18n_tool/tencent_chat_i18n_tool.dart';
import 'package:tencent_cloud_chat_demo/src/about.dart';
import 'package:tencent_cloud_chat_demo/src/my_profile_detail.dart';
import 'package:tencent_cloud_chat_demo/src/pages/skin/skin_page.dart';
import 'package:tencent_cloud_chat_demo/src/qrcode.dart';
import 'package:tencent_cloud_chat_demo/utils/authService.dart';
import 'package:tencent_cloud_chat_demo/utils/constant.dart';
import 'package:tencent_cloud_chat_demo/utils/request.dart';
import 'package:tencent_cloud_chat_sdk/manager/v2_tim_manager.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_friend_info.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_demo/src/pages/login.dart';
import 'package:tencent_cloud_chat_demo/src/provider/local_setting.dart';
import 'package:tencent_cloud_chat_demo/src/provider/login_user_Info.dart';
import 'package:tencent_cloud_chat_demo/src/provider/theme.dart';
import 'package:tencent_cloud_chat_demo/src/routes.dart';
import 'package:tencent_cloud_chat_demo/utils/theme.dart';
import 'package:tencent_cloud_chat_demo/utils/toast.dart';
import 'package:adaptive_action_sheet/adaptive_action_sheet.dart';
import 'package:tencent_cloud_chat_uikit/theme/color.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/screen_utils.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class MyProfile extends StatefulWidget {
  const MyProfile({
    Key? key,
  }) : super(key: key);
  @override
  State<StatefulWidget> createState() => _ProfileState();
}

class _ProfileState extends State<MyProfile> {
  final CoreServicesImpl _coreServices = TIMUIKitCore.getInstance();
  final V2TIMManager sdkInstance = TIMUIKitCore.getSDKInstance();
  final TIMUIKitProfileController _timuiKitProfileController =
      TIMUIKitProfileController();
  String? userID;

  String _getAllowText(int? allowType) {
    if (allowType == 0) {
      return TIM_t("允许任何人");
    }

    if (allowType == 1) {
      return TIM_t("需要验证信息");
    }

    if (allowType == 2) {
      return TIM_t("禁止加我为好友");
    }

    return TIM_t("未指定");
  }

  _handleLogout() async {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '温馨提示',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 12),
                const Text(
                  '确定要退出登录么？',
                  style: TextStyle(fontSize: 15),
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          side: const BorderSide(color: Colors.grey),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () async {
                          try {
                            final res = await _coreServices.logout();
                            if (res.code == 0) {
                              try {
                                AuthService.clearLoginState();
                                Future<SharedPreferences> _prefs =
                                    SharedPreferences.getInstance();
                                SharedPreferences prefs = await _prefs;
                                prefs.remove(Const.DEV_LOGIN_USER_ID);
                                prefs.remove(Const.DEV_LOGIN_USER_SIG);
                                prefs.remove(Const.SMS_LOGIN_TOKEN);
                                prefs.remove(Const.SMS_LOGIN_PHONE);
                                Routes().directToLoginPage();
                              } catch (err) {
                                ToastUtils.log('someError');
                                ToastUtils.log(err);
                              }
                            } else {
                              ToastUtils.toast(TIM_t("退出登录失败"));
                              Navigator.pop(context);
                            }
                          } catch (e) {
                            print(e);
                          }
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  changeFriendVerificationMethod(int allowType) async {
    _timuiKitProfileController.changeFriendVerificationMethod(allowType);
  }

  showApplicationTypeSheet(theme) async {
    const allowAny = 0;
    const neddConfirm = 1;
    const denyAny = 2;

    showAdaptiveActionSheet(
      context: context,
      actions: <BottomSheetAction>[
        BottomSheetAction(
          title: Text(
            TIM_t("允许任何人"),
            style: TextStyle(color: theme.primaryColor, fontSize: 18),
          ),
          onPressed: (_) {
            changeFriendVerificationMethod(allowAny);
            Navigator.of(context, rootNavigator: true).pop();
          },
        ),
        BottomSheetAction(
            title: Text(
              TIM_t("需要验证信息"),
              style: TextStyle(color: theme.primaryColor, fontSize: 18),
            ),
            onPressed: (_) {
              changeFriendVerificationMethod(neddConfirm);
              Navigator.of(context, rootNavigator: true).pop();
            }),
        BottomSheetAction(
          title: Text(
            TIM_t("禁止加我为好友"),
            style: TextStyle(color: theme.primaryColor, fontSize: 18),
          ),
          onPressed: (_) {
            changeFriendVerificationMethod(denyAny);
            Navigator.of(context, rootNavigator: true).pop();
          },
        ),
      ],
      cancelAction: CancelAction(
        title: Text(
          TIM_t("取消"),
          style: const TextStyle(fontSize: 18),
        ),
      ), // onPressed parameter is optional by default will dismiss the ActionSheet
    );
  }

  String cAccount = '';

  @override
  void initState() {
    super.initState();
  }

  /// 注销账号
  Future<void> deRegister() async {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '温馨提示',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 12),
                const Text(
                  '确定要注销账号么？',
                  style: TextStyle(fontSize: 15),
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          side: const BorderSide(color: Colors.grey),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () async {
                          Navigator.of(context).pop();
                          EasyLoading.show(status: '正在注销账号...');
                          final userSig = await AuthService.getAuthToken();
                          try {
                            final res = await appRequest(
                              method: 'post',
                              path:
                                  'https://yunpengim.daboluo.pro/api/user/deletion_request',
                              data: {
                                'usersig': userSig,
                                'reason': '用户主动注销账号',
                              },
                            );
                            debugPrint(
                                'deletion_request status response: ${res.data}');
                            if (res.data?['code'] == 0) {
                              ToastUtils.toast(
                                  TIM_t(res.data?['msg'] ?? '注销账号申请已提交，请等待审核'));
                            } else {
                              ToastUtils.toast(
                                  TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
                            }
                          } catch (e) {
                            print(e);
                          } finally {
                            EasyLoading.dismiss();
                          }
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  /// 投诉建议
  Future<void> complaint() async {
    String content = '';
    String contact = '';
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Text(
                  '投诉建议',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 12),
                TextField(
                  decoration: const InputDecoration(
                    labelText: '请输入您的建议',
                    border: OutlineInputBorder(),
                  ),
                  maxLines: 3,
                  onChanged: (value) {
                    content = value;
                  },
                ),
                const SizedBox(height: 12),
                TextField(
                  decoration: const InputDecoration(
                    labelText: '联系方式（可选）',
                    border: OutlineInputBorder(),
                  ),
                  onChanged: (value) {
                    contact = value;
                  },
                ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Expanded(
                      child: OutlinedButton(
                        style: OutlinedButton.styleFrom(
                          side: const BorderSide(color: Colors.grey),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text(
                          '取消',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.black,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(22),
                          ),
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        onPressed: () async {
                          if (content.trim().isEmpty) {
                            ToastUtils.toast('请填写建议内容');
                            return;
                          }
                          try {
                            final userSig = await AuthService.getAuthToken();
                            final res = await appRequest(
                              method: 'post',
                              path:
                                  'https://yunpengim.daboluo.pro/api/feedback/complaint',
                              data: {
                                'usersig': userSig,
                                'content': content,
                                'contact': contact,
                              },
                            );
                            debugPrint(
                                'complaint status response: ${res.data}');
                            if (res.data?['code'] == 0) {
                              ToastUtils.toast(TIM_t(
                                  res.data?['msg'] ?? '感谢您的建议，我们讲尽快审核并回复您'));
                            } else {
                              ToastUtils.toast(
                                  TIM_t(res.data?['msg'] ?? '网络故障，请稍后重试'));
                            }
                          } catch (e) {
                            print(e);
                          } finally {
                            Navigator.of(context).pop();
                          }
                        },
                        child: const Text(
                          '提交',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    cAccount = cAccount.isEmpty ? AuthService.account : cAccount;
    final LocalSetting localSetting = Provider.of<LocalSetting>(context);
    final themeType = Provider.of<DefaultThemeData>(context).currentThemeType;
    final theme = Provider.of<DefaultThemeData>(context).theme;
    final loginUserInfoModel = Provider.of<LoginUserInfo>(context);
    final bool isWideScreen =
        TUIKitScreenUtils.getFormFactor() == DeviceType.Desktop;
    final V2TimUserFullInfo loginUserInfo = loginUserInfoModel.loginUserInfo;
    return TIMUIKitProfile(
      isSelf: true,
      userID: loginUserInfo.userID ?? "",
      controller: _timuiKitProfileController,
      builder: (BuildContext context, V2TimFriendInfo userInfo,
          V2TimConversation conversation, int friendType, bool isMute) {
        final userProfile = userInfo.userProfile;
        userProfile?.userID = cAccount;
        final int? allowType = userProfile?.allowType;

        final allowText = _getAllowText(allowType);
        return SingleChildScrollView(
            child: Column(
          children: [
            GestureDetector(
              onTap: () async {
                final String account = cAccount;
                final email = await AuthService.getEmail();
                Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => MyProfileDetail(
                          userProfile: userProfile,
                          controller: _timuiKitProfileController,
                          account: account,
                          email: email,
                          updateInfo: (String newAccount) {
                            setState(() {
                              cAccount = newAccount;
                            });
                          })),
                );
              },
              child: TIMUIKitProfileUserInfoCard(
                userInfo: userProfile,
                showArrowRightIcon: true,
              ),
            ),
            // 二维码名片
            Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              child: InkWell(
                onTap: () async {
                  final account = cAccount;
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => Qrcode(
                        account: account,
                      ),
                    ),
                  );
                },
                child: TIMUIKitOperationItem(
                  isEmpty: false,
                  operationName: TIM_t("二维码名片"),
                ),
              ),
            ),

            // 好友验证方式选
            Container(
              margin: const EdgeInsets.symmetric(vertical: 10),
              child: InkWell(
                onTap: () {
                  showApplicationTypeSheet(theme);
                },
                child: TIMUIKitOperationItem(
                  isEmpty: false,
                  operationName: TIM_t("加我为好友的方式"),
                  operationRightWidget: Text(
                    allowText,
                    textAlign: isWideScreen ? null : TextAlign.end,
                  ),
                ),
              ),
            ),
            InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const SkinPage(),
                  ),
                );
              },
              child: TIMUIKitOperationItem(
                isEmpty: false,
                operationName: TIM_t("更换皮肤"),
                operationRightWidget: Text(
                    DefTheme.defaultThemeName[themeType]!,
                    textAlign: isWideScreen ? null : TextAlign.end,
                    style: TextStyle(color: theme.primaryColor)),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            // TIMUIKitOperationItem(
            //   isEmpty: false,
            //   operationName: TIM_t("消息阅读状态"),
            //   operationDescription:
            //       TIM_t("关闭后，您收发的消息均不带消息阅读状态，您将无法看到对方是否已读，同时对方也无法看到你是否已读。"),
            //   type: "switch",
            //   operationValue: localSetting.isShowReadingStatus,
            //   onSwitchChange: (bool value) {
            //     localSetting.isShowReadingStatus = value;
            //     if (value) {
            //       ToastUtils.toast(TIM_t("该功能为旗舰版功能"));
            //     }
            //   },
            // ),
            // const SizedBox(
            //   height: 10,
            // ),
            TIMUIKitOperationItem(
              isEmpty: false,
              operationName: TIM_t("显示在线状态"),
              operationDescription: TIM_t("关闭后，您将不可以在会话列表和通讯录中看到好友在线或离线的状态提示。"),
              type: "switch",
              operationValue: localSetting.isShowOnlineStatus,
              onSwitchChange: (bool value) {
                localSetting.isShowOnlineStatus = value;
              },
            ),
            const SizedBox(
              height: 10,
            ),
            InkWell(
              onTap: () {
                complaint();
              },
              child: TIMUIKitOperationItem(
                isEmpty: false,
                operationName: TIM_t("投诉建议"),
                operationRightWidget: const Text(""),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            InkWell(
              onTap: () {
                deRegister();
              },
              child: TIMUIKitOperationItem(
                isEmpty: false,
                operationName: TIM_t("注销账号"),
                operationRightWidget: const Text(""),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            InkWell(
              onTap: _handleLogout,
              child: Container(
                alignment: Alignment.center,
                padding: const EdgeInsets.symmetric(vertical: 15),
                decoration: BoxDecoration(
                    color: Colors.white,
                    border: Border(
                        bottom: BorderSide(color: hexToColor("E5E5E5")))),
                child: Text(
                  TIM_t("退出登录"),
                  style: TextStyle(color: hexToColor("FF584C"), fontSize: 17),
                ),
              ),
            )
          ],
        ));
      },
    );
  }
}
